package it.azienda.framework.modello;

import it.azienda.framework.controllo.AzioneBase;
import it.azienda.framework.utilita.Utilita;
import it.azienda.framework.persistenza.DAOConnectionSingleton;
import it.azienda.framework.persistenza.DAOException;
import it.azienda.framework.persistenza.DaoBase;
import it.azienda.moretti.modello.BeanUtente;
import java.io.Serializable;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.Query;

public class BeanBase implements Serializable, java.lang.Comparable {

    public Object dettaglio(Object idBean)
            throws Exception {
        BeanBase beanBase;
        Exception exception;
        Session sess = null;
        Transaction tr = null;
        beanBase = new BeanBase();
        //primaDettaglio();

        try {
            sess = DAOConnectionSingleton.newSession();
            //primaDettaglioInSession();
            beanBase = (BeanBase) sess.get(getClass(), (Serializable) idBean);
            //dopoDettaglioInSession();
            sess.flush();
        } catch (HibernateException hex) {
            try {
                DAOConnectionSingleton.rollbackTransaction();
            } catch (Exception e) {
            }

            throw hex;
        } finally {
            DAOConnectionSingleton.closeSession();
        }
        //dopoDettaglio();
        return beanBase;
    }

    public void modifica() throws Exception {
        DaoBase dao = new DaoBase();
        try {
            dao.modifica(this);
        } catch (Exception daoe) {
            throw daoe;
        }
    }

    public void inserisci() throws Exception {
        DaoBase dao = new DaoBase();
        try {
            dao.inserisci(this);
        } catch (Exception daoe) {
            throw daoe;
        }
    }

    public void cancella() throws Exception {
        DaoBase dao = new DaoBase();
        try {
            dao.cancella(this);
        } catch (Exception daoe) {
            throw daoe;
        }
    }

    public ArrayList caricaTutti(String bean) {
        Session sessione = DAOConnectionSingleton.newSession();
        ArrayList obj = null;
        try {
            BeanUtente login = (BeanUtente) Utilita.getSession().getAttribute("login");
            Query q = sessione.getNamedQuery("tutti" + bean);
            String queryS = q.getQueryString();

            try {
                obj = (ArrayList) q.list();
            } catch (Exception ee) {
                obj = (ArrayList) q.list();
            }
        } catch (Exception ex) {
            ex.printStackTrace();
            System.out.println("errore: " + ex.getCause());
            try {
            } catch (Exception exc) {
                System.out.println("errore: " + exc.toString());
            }
        } finally {
            DAOConnectionSingleton.closeSession();
        }
        return obj;
    }

    public ArrayList caricaTuttiStorico(String bean, java.lang.Long idPadre) {
        Session sessione = DAOConnectionSingleton.newSession();
        ArrayList obj = null;
        try {
            DAOConnectionSingleton.beginTransaction();
            obj = (ArrayList) sessione.getNamedQuery("tuttiStorico" + bean).setParameter("id", idPadre).list();
            DAOConnectionSingleton.commitTransaction();

        } catch (DAOException ex) {
            ex.printStackTrace();
            System.out.println("errore" + ex.getCause());
            try {
                DAOConnectionSingleton.rollbackTransaction();
            } catch (DAOException exc) {
            }
        } finally {
            DAOConnectionSingleton.closeSession();
        }
        return obj;
    }

    public ArrayList caricaProfilo(String bean) {
        Session sessione = DAOConnectionSingleton.newSession();
        ArrayList obj = null;
        BeanUtente login = (BeanUtente) Utilita.getSession().getAttribute("login");
        try {
            DAOConnectionSingleton.beginTransaction();
            obj = (ArrayList) sessione.getNamedQuery("profilo" + bean).setString("nomeutente", login.getEmail()).setString("passwd", login.getPassword()).list();
            DAOConnectionSingleton.commitTransaction();

        } catch (DAOException ex) {
            ex.printStackTrace();
            System.out.println("errore" + ex.getCause());
            try {
                DAOConnectionSingleton.rollbackTransaction();
            } catch (DAOException exc) {
            }
        } finally {
            DAOConnectionSingleton.closeSession();
        }
        return obj;
    }

    public ArrayList caricaPrenotazioneUtente(String bean) {
        Session sessione = DAOConnectionSingleton.newSession();
        ArrayList obj = null;
        BeanUtente login = (BeanUtente) Utilita.getSession().getAttribute("login");
        try {
            DAOConnectionSingleton.beginTransaction();
            obj = (ArrayList) sessione.getNamedQuery("tuttiPrenotazioneUtente").setLong("idUtente", login.getId()).list();
            DAOConnectionSingleton.commitTransaction();

        } catch (DAOException ex) {
            ex.printStackTrace();
            System.out.println("errore" + ex.getCause());
            try {
                DAOConnectionSingleton.rollbackTransaction();
            } catch (DAOException exc) {
            }
        } finally {
            DAOConnectionSingleton.closeSession();
        }
        return obj;
    }

    public int compareTo(Object obj) {
        return 0;
    }

    public final void refreshLazyAssociation(String classe, String proprieta, String nomeBean) {
        Transaction tr = null;
        Session session = null;
        Object obj = null;
        Method method = null;
        String primaLettera = proprieta;
        String restoStringa = proprieta;
        primaLettera = primaLettera.substring(0, 1);
        restoStringa = restoStringa.substring(1, proprieta.length());
        proprieta = primaLettera.toUpperCase() + restoStringa;
        String metodoProprieta = "set" + proprieta;

        try { //AzioneBase.pkg

            DAOConnectionSingleton.beginTransaction();
            Class cls = Class.forName(classe);
            method = cls.getMethod("get" + proprieta, new Class[]{});
            Iterator it = ((Set) method.invoke(this, new Object[]{})).iterator();
            System.out.println("assss" + it.toString());
            while (it.hasNext()) {
                it.next();
            }
            DAOConnectionSingleton.commitTransaction();
        } catch (Exception ex) {
            Throwable t = ex.getCause();
            try {
                DAOConnectionSingleton.rollbackTransaction();
            } catch (Exception ec) {
            } finally {
                DAOConnectionSingleton.closeSession();
            }

        } finally {

        }
    }

    public void caricaStorici(String nomeBean) {
        try {
            Class classe = Class.forName(AzioneBase.pkg + nomeBean);
            Method[] metodi = classe.getMethods();
            boolean chiudiSessione = false;
            Session s = (Session) DAOConnectionSingleton.getThreadSession().get();
            if (s == null) {
                DAOConnectionSingleton.newSession();
                chiudiSessione = true;
            }
            DAOConnectionSingleton.beginTransaction();
            for (int i = metodi.length; i > 0; i--) {
                Method metodo = metodi[i - 1];
                String nomeMetodo = metodo.getName();
                if (nomeMetodo.startsWith("getLazy")) {
                    myRefreshLazyAssociation(AzioneBase.pkg + nomeBean, "get" + nomeMetodo.substring(7));
                }
            }
            DAOConnectionSingleton.commitTransaction();
            if (chiudiSessione) {
                DAOConnectionSingleton.closeSession();
            }
        } catch (DAOException ex) {
            ex.printStackTrace();
        } catch (ClassNotFoundException ex) {
            ex.printStackTrace();
        } catch (SecurityException ex) {
            ex.printStackTrace();
        }
    }

    public final void myRefreshLazyAssociation(String classe, String metodo) {
        Class cls = null;
        Method method = null;
        Iterator it = null;
        try {
            cls = Class.forName(classe);
            method = cls.getMethod(metodo, new Class[]{});
            Set set = (Set) method.invoke(this, new Object[]{});
            it = set.iterator();
            if (it != null) {
                System.out.println("myRefreshLazyAssociation " + it.toString());
                while (it.hasNext()) {
                    it.next();
                }
            } else {
                method = cls.getMethod("s" + metodo.substring(1), new Class[]{Set.class});
                method.invoke(this, new Object[]{new HashSet()});
            }
        } catch (ClassNotFoundException ex) {
            ex.printStackTrace();
        } catch (SecurityException ex) {
            ex.printStackTrace();
        } catch (NoSuchMethodException ex) {
            ex.printStackTrace();
        } catch (IllegalArgumentException ex) {
            ex.printStackTrace();
        } catch (IllegalAccessException ex) {
            ex.printStackTrace();
        } catch (InvocationTargetException ex) {
            ex.printStackTrace();
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }
}
